package com.example.robot;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RobotActivity extends AppCompatActivity {
    private ListView listView;
    private ChatAdapter chatAdapter;
    private List<ChatBean> chatBeanList;
    private EditText et_send_msg;
    private Button btn_send;
    //聊天网站地址
    private static final String WEB_SITE="http://api.qingyunke.com/api.php";  //青云客
    private static final String  KEY="free";   //青云客
    private String sendMsg;                    //发送的消息
    private String[] welcome;                  //存储欢迎消息
    private MHandler mHandler;
    public static final int MSG_OK=1;      //获取数据成功
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robot);
        chatBeanList=new ArrayList<ChatBean>();
        mHandler=new MHandler();
        //获取本地内置的欢迎消息
        welcome=getResources().getStringArray(R.array.welcome);
        initView();     //初始化界面
    }

    private void initView() {
        listView=(ListView) findViewById(R.id.list);
        et_send_msg=(EditText) findViewById(R.id.et_send_msg);
        btn_send=(Button) findViewById(R.id.btn_send);
        chatAdapter=new ChatAdapter(chatBeanList,this);
        listView.setAdapter(chatAdapter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendData();     //点击发送按钮，发送信息
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if(keyCode==KeyEvent.KEYCODE_ENTER && keyEvent.getAction()==KeyEvent.ACTION_DOWN){
                    sendData();
                }
                return false;
            }
        });
        int position=(int)(Math.random()*welcome.length-1);
        showData(welcome[position]);
    }

    private void sendData() {
        sendMsg=et_send_msg.getText().toString();
        if(TextUtils.isEmpty(sendMsg)){
            Toast.makeText(this, "您还未输入任何信息哦", Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        sendMsg=sendMsg.replaceAll(" ","").replaceAll("\n","").trim();
        //显示要发送的消息
        ChatBean chatBean=new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(ChatBean.SEND);
        chatBeanList.add(chatBean);
        chatAdapter.notifyDataSetChanged();
        getDataFromServer();       //从服务器获取消息
    }

    private void getDataFromServer() {
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request=new Request.Builder().url(WEB_SITE+"?key="+KEY+"&msg="+sendMsg).build();
        Log.i("TAG", "getDataFromServer: "+request);
        Call call=okHttpClient.newCall(request);
        //开启异步线程访问网络
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("TAG", "onFailure:error!"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res=response.body().string();
                Message msg=new Message();
                msg.what=MSG_OK;
                msg.obj=res;
                mHandler.sendMessage(msg);
            }
        });
    }
    class MHandler extends Handler {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what){
                case MSG_OK:
                    if(msg!=null){
                        String vlResult=(String)msg.obj;
                        ParseData(vlResult);
                    }
                    break;
            }
        }

        private void ParseData(String jsonData) {
            try {
                JSONObject obj=new JSONObject(jsonData);
                String content=obj.getString("content");
                content=content.replaceAll(" ","").replace("{br}","\n");
                int code=obj.getInt("result");
                updateView(code,content);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateView(int code, String content) {
        switch (code){
            case 4004:
                showData("主人，今天我累了，我要休息了，明天再来找我耍吧");
                break;
            case 4005:
                showData("主人，你说的是外星语吗？");
                break;
            case 4006:
                showData("主人，我今天要求约会哦，暂不聊天啦");
                break;
            case 4007:
                showData("主人，明天再和你耍啦，我生病了，呜呜。。。。。。");
                break;
            default:
                showData(content);
                break;
        }
    }
    //显示接收的消息
    private void showData(String message) {
        ChatBean chatBean=new ChatBean();
        chatBean.setMessage(message);
        chatBean.setState(ChatBean.RECEIVE);
        chatBeanList.add(chatBean);
        chatAdapter.notifyDataSetChanged();
    }

    private long exitTime;//记录第一次单击的时间

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK && event.getAction()==KeyEvent.ACTION_DOWN){
            if(System.currentTimeMillis()-exitTime>2000){
                Toast.makeText(this, "再按一次退出智能聊天程序", Toast.LENGTH_SHORT).show();
                exitTime=System.currentTimeMillis();
            }else{
                RobotActivity.this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
